import 'package:flutter/material.dart';

/// Android双击返回键,退出App
class DoubleTapBackExitApp extends StatefulWidget {
  const DoubleTapBackExitApp({
    Key? key,
    required this.child,
    this.showMessage,
    this.duration = const Duration(milliseconds: 2500),
  }) : super(key: key);

  final Widget child;
  final Function? showMessage;

  /// 两次点击返回按钮的时间间隔
  final Duration duration;

  @override
  _DoubleTapBackExitAppState createState() => _DoubleTapBackExitAppState();
}

class _DoubleTapBackExitAppState extends State<DoubleTapBackExitApp> {
  DateTime? _lastTime;

  @override
  Widget build(BuildContext context) {
    return PopScope<bool>(
      canPop: false,
      onPopInvokedWithResult: _isExit,
      child: widget.child,
    );
  }

  Future<bool> _isExit(bool didPop, bool? result) {
    if (!didPop) {
      if (_lastTime == null ||
          DateTime.now().difference(_lastTime!) > widget.duration) {
        _lastTime = DateTime.now();
        if (widget.showMessage != null) {
          widget.showMessage!();
        }
        return Future.value(true);
      }
    }
    return Future.value(false);
  }
}
